<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>拉流页面</title>
</head>

<body>
<video id="video" style="width: 800px; height: 600px;" muted></video>
<script>
  let pc, ws
  const waitWebsocketReady = (ws) => {
    return new Promise((resolve, reject) => {
      ws.onopen = () => {resolve()}
    })
  }
  const init = async () => {
    pc = new RTCPeerConnection()
    ws = new WebSocket('ws://127.0.0.1:9000')
    let videoDom = document.getElementById("video")
    await waitWebsocketReady(ws)
    ws.send('subscribe')
    ws.addEventListener('message', async (event) => {
      let msg = JSON.parse(event.data)
      console.log('ws接收', msg)
      switch (msg.type) {
        case "offer":
          await pc.setRemoteDescription(msg)
          const answer = await pc.createAnswer()
          await pc.setLocalDescription(answer)
          ws.send(JSON.stringify(answer))
          break
        default:
          await pc.addIceCandidate(msg);
          break
      }
    })
    pc.addEventListener('icecandidate', (event) => {
      console.log('icecandidate', event)
      if (event.candidate) {
        ws.send(JSON.stringify(event.candidate))
      }
    })
    pc.addEventListener('track', (event) => {
      console.log('track', event)
      videoDom.srcObject = event.streams[0]
      videoDom.oncanplay = () => {
        videoDom.play()
      }
    })
  }
  init()
</script>
</body>

</html>
